package com.info.zhiduoduo.core.service.payment.project;

import com.baomidou.mybatisplus.mapper.Condition;
import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.configs.KltPayConfig;
import com.info.zhiduoduo.common.configs.PayConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.pay.PayPrefix;
import com.info.zhiduoduo.common.constants.pay.PayTypeSn;
import com.info.zhiduoduo.common.constants.system.UserType;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.common.utils.RandomUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.service.*;
import com.info.zhiduoduo.core.service.impl.CeoNoticeService;
import com.info.zhiduoduo.core.service.payment.thirdpay.AliPayService;
import com.info.zhiduoduo.core.service.payment.thirdpay.PinganPayService;
import com.info.zhiduoduo.core.service.payment.thirdpay.ZhaoShangPayService;
import com.info.zhiduoduo.repository.entity.company.CompanyPayment;
import com.info.zhiduoduo.repository.entity.company.CompanyProject;
import com.info.zhiduoduo.repository.entity.company.CompanyProjectRepairRecord;
import com.info.zhiduoduo.repository.entity.maker.MakerBankcard;
import com.info.zhiduoduo.repository.entity.order.TradeRecord;
import com.info.zhiduoduo.repository.mapper.company.CompanyPaymentMapper;
import com.info.zhiduoduo.repository.mapper.company.CompanyProjectMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceAccountMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectItemMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerStudioMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerBrokerageMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerCompanyMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerSubMapper;
import com.info.zhiduoduo.repository.mapper.pay.PaymentMerchantMapper;
import com.info.zhiduoduo.repository.mapper.system.ProjectCategoryMapper;
import com.info.zhiduoduo.repository.mapper.taxer.TaxerInvoiceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;

/**
 * 企业使用九歌统一商户号支付项目款的业务逻辑
 */
@Slf4j
@Service
@Transactional
public class ProjectJiugeUnifyPaymentServiceImpl extends BaseProjectJiugePaymentService {

    @Autowired
    MakerMapper makerMapper;
    @Autowired
    PartnerCompanyMapper partnerCompanyMapper;
    @Autowired
    PartnerBrokerageMapper partnerBrokerageMapper;
    @Autowired
    ProjectCategoryMapper projectCategoryMapper;
    @Autowired
    CompanyProjectMapper projectMapper;
    @Autowired
    CrowdsourceAccountMapper crowdsourceAccountMapper;
    @Autowired
    CrowdsourceProjectItemMapper crowdsourceProjectItemMapper;
    @Autowired
    CrowdsourceProjectMapper crowdsourceProjectMapper;
    @Autowired
    MakerStudioMapper makerStudioMapper;
    @Autowired
    TaxerInvoiceMapper taxerInvoiceMapper;
    @Autowired
    PartnerSubMapper partnerSubMapper;
    @Autowired
    PartnerMapper partnerMapper;
    @Autowired
    CompanyPaymentMapper companyPaymentMapper;
    @Autowired
    PaymentMerchantMapper paymentMerchantMapper;

    @Autowired
    CoreCompanyService coreCompanyService;
    @Autowired
    DingdingNoticeService dingdingNoticeService;
    @Autowired
    WxMessageService wxMessageService;
    @Autowired
    WxPartnerMessageService wxPartnerMessageService;
    @Autowired
    WxCrowdsourceMessageService wxCrowdsourceMessageService;
    @Autowired
    CeoNoticeService ceoNoticeService;
    @Autowired
    CoreProjectService coreProjectService;
    @Autowired
    ZhiduoduoProjectService zhiduoduoProjectService;
    @Autowired
    CoreBrokerageService coreBrokerageService;

    // ************** 具体的第三方支付平台 ************//
//    @Autowired
//    DaysPayService daysPayService;
//    @Autowired
//    TransferPayService transferPayService;
    @Autowired
    ZhaoShangPayService zhaoShangPayService;
    @Autowired
    AliPayService aliPayService;
    @Autowired
    PinganPayService pinganPayService;
    @Autowired
    CommonConfig commonConfig;
    @Autowired
    ZddUrlConfig zddUrlConfig;
    @Autowired
    PayConfig payConfig;
    @Autowired
    KltPayConfig kltPayConfig;

    @Override
    public SmartResult handlePayment(CompanyProject project) {
        return handlePayUser(project);
    }

    @Override
    public SmartResult handlePayUser(CompanyProject project) {
        Integer projectid = project.getProjectid();
        Integer userid = project.getUserid();
        CompanyPayment companyPayment = companyPaymentMapper.getCompanyPayment(project.getCompid(),project.getPayId());
        if(companyPayment == null) {
            return SmartResult.fail(StatusMsg.StatusMsg_330);
        }
        //实际给创客的金额
        BigDecimal payUserAmount = project.getProjectPayAmount();

        //专票项目，使用对公账户，普票项目，使用个人账户
        Integer invoicetype = project.getInvoicetype();
        int accttype = invoicetype != null && invoicetype == 2 ? Constants.BANK_ACCT_TYPE_COMPANY : Constants.BANK_ACCT_TYPE_PERSONAL;
        MakerBankcard bankcard = new MakerBankcard().selectOne(
                Condition.create().eq("userid", userid).eq("state", 1).eq("accttype", accttype).last("limit 1"));

        if (bankcard == null) {
            return SmartResult.fail(StatusMsg.StatusMsg_206);
        }

        //支付记录,检查是否已存在还未处理好的支付记录.如果有,那么需要等待
        //支付创建中,处理中和处理成功,表示不需要再新建了.直接返回
        int recordProcessing = new TradeRecord().selectCount(Condition.create()
                .eq("projectid", projectid)
                .eq("idtype", UserType.MAKER)
                .eq("business_type", Constants.KLT_PAY_BUSINESS_TYPE_USER_AMOUNT)
                .in("tradestate", Arrays.asList(Constants.TRADE_CREATE, Constants.TRADE_IN_PROCESS, Constants.TRADE_SUCCESS)));
        if (recordProcessing > 0) {
            return SmartResult.fail(StatusMsg.StatusMsg_448);
        }

        String purpose = project.getProjectname() + "-项目款";
        if (purpose.length() > 16) {
            purpose = purpose.substring(0, 16);
        }

        //2022.6.6 支付宝转账方式判断
        String acctno = bankcard.getAcctno();
        String bankno = bankcard.getBankno();
        String bankname = bankcard.getBankname();
        String openAcctBankName = bankcard.getOpenAcctBankName();
        if (PayTypeSn.ZFB.equals(companyPayment.getPayTypeSn())) {
            if (StringUtil.isNotEmpty(bankcard.getAlipayAccount())) {
                acctno = bankcard.getAlipayAccount();
                bankname = "支付宝转账";
                openAcctBankName = "支付宝";
                bankno = "aliPay";
            } else {
                return SmartResult.fail(StatusMsg.StatusMsg_484);
            }
        }
        String tradeno = RandomUtil.createRandomNo(PayPrefix.ZDD, "");
        //平安银行交易码小于20
        if (PayTypeSn.PA.equals(companyPayment.getPayTypeSn())) {
            tradeno = RandomUtil.createRandomNoForPingan(PayPrefix.ZDD, "");
        }
        TradeRecord trade = new TradeRecord().setAcctname(bankcard.getPayername())
                                             .setBankname(bankname)
                                             .setBankno(bankno)
                                             .setBranchName(openAcctBankName)
                                             .setBankProvince(bankcard.getProvince())
                                             .setBankCity(bankcard.getCity())
                                             .setAcctno(acctno)
                                             .setAccttype(bankcard.getAccttype())
                                             .setPurpose(purpose)
                                             .setTradeamount(payUserAmount)
                                             .setTradeno(tradeno)
                                             .setTradetime(new Date())
                                             .setTradetype(Constants.TRADE_TYPE_PAYMENT)
                                             .setPayId(project.getPayId())
                                             .setBusinessType(Constants.KLT_PAY_BUSINESS_TYPE_USER_AMOUNT)
                                             .setProjectid(projectid)
                                             .setIdtype(1)
                                             .setUserid(userid)
                                             .setMerchantid(companyPayment.getSourceId());// 设置支付商户ID

        if (trade.insert()) {

			//判断企业不是属于修复数据，如果属于则不走支付接口，直接返回成功
			CompanyProjectRepairRecord repairRecord = new CompanyProjectRepairRecord().selectOne(Condition.create().eq("project_id",project.getProjectid()));
			if (null != repairRecord) {
				LogUtil.info(" 修复数据-直接返回成功");
				return SmartResult.success();
			}

            // 支付
            if (companyPayment.getSourceTable() == 1) {
                // 招商银行支付方式
                if (PayTypeSn.ZS.equals(companyPayment.getPayTypeSn())) {
                    return zhaoShangPayService.doCallPayApi(trade);
                }
                //平安银行支付方式
                else if (PayTypeSn.PA.equals(companyPayment.getPayTypeSn())) {
                    return pinganPayService.doCallPayApi(trade);
                }
            } else if (companyPayment.getSourceTable() == 2) {
                // 支付宝商户支付
                return aliPayService.doCallPayApi(trade);
            }
		}
		return SmartResult.fail(StatusMsg.StatusMsg_445);
	}

}
